var createError = require('http-errors');
var express = require('express');
const { createServer } = require("http");
const { Server } = require("socket.io");
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors'); // 导入 cors 模块
// 解析 token
var config = require('./jwtSecretKey')
const expressJWT = require('express-jwt')
// 导入自定义中间件
const dispatch = require('./middleware/dispatch');
const errorHandler = require('./middleware/globalrror')
// 前台接口
const front_Ai = require('./routes/front/Ai');
const front_article = require('./routes/front/article');
const front_comment = require('./routes/front/comment');
const front_user = require('./routes/front/user');
const front_login = require('./routes/front/login');
const front_chat = require('./routes/front/chat');
// 后台接口
const back_login = require('./routes/back/login');
const back_article = require('./routes/back/article');
const back_categories = require('./routes/back/categories');
const back_tags = require('./routes/back/tags');


var app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: ["http://localhost:5173"], // 客户端路径及端口
    methods: ["GET", "POST"]
  },
});


const fixedRoomName = 'defaultRoom';

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.join(fixedRoomName);
  const room = socket.adapter.rooms.get(fixedRoomName).size
  console.log(room);
  socket.emit("num", room)
  socket.to(fixedRoomName).emit("num", room)

  socket.on("publish", (data) => {
    // console.log("收到", data);
    socket.emit('message', data)
    socket.to(fixedRoomName).emit('message', data)
  });

  socket.on('disconnect', () => {
    console.log('离开');
    // 在这里可以执行用户离开时的清理或其他操作
    // const room = socket.adapter.rooms.get(fixedRoomName).size
    if (socket.adapter.rooms.get(fixedRoomName) == undefined) {
      return
    } else {
      // console.log("room", socket.adapter.rooms.get(fixedRoomName));
      socket.emit("num", room)
      socket.to(fixedRoomName).emit("num", room)
    }

  });
});




// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 添加跨域支持
app.use(cors());

// 注册中间件
app.use(dispatch);
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^(?!.*api).*/] }))
app.use(errorHandler)

// 注册路由
app.use('/front/Ai', front_Ai);
app.use('/front/article', front_article);
app.use('/front/comment', front_comment);
app.use('/front/user', front_user);
app.use('/front/login', front_login);
app.use('/front/chat', front_chat);

app.use('/back/login', back_login);
app.use('/back/article', back_article);
app.use('/back/categories', back_categories);
app.use('/back/tags', back_tags);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = httpServer;
